iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0

為什麼要寫日誌(Log)

Log 主要是要記錄錯誤以及警告,而不是讓工程師寫心情小語。

為什麼要記錄錯誤呢?有錯就直接噴給使用者,讓使用者通知工程師、用客服信箱紀錄錯誤不就好啦。

這篇文章要告訴各位大老闆,為什麼應該要有自己的通知系統與紀錄系統。

當發生緊急狀況例如服務崩潰時,通知系統可以立刻通知 on call 工程師,讓他知道哪裡有問題、出什麼問題,這樣他可以盡快掌握狀況。而身為老闆的你也就可以傳 Line 跟工程師說這是你負責的部分,如果你休假也沒在幹嘛就負責修一下你自己寫的 bug。

紀錄系統可以幫助我們記錄一些重要資訊,以便日後出錯時有跡可循。例如,還有對接外部 API 時出了狀況,如果有這些 log,我們就可以自信地把鍋甩回去給對方的工程師。

怎麼開始寫日誌

被動的日記
當程式拋出錯誤(Error)時,laravel helper 會自動記錄 log 預設是 stack,會存在 app/storage/logs/laravel.log
https://laravel-guide.readthedocs.io/en/latest/errors/

LOG_CHANNEL=daily

可以將 .env 的 LOG_CHANEL 改成 daily,這樣每天的 log 會在不同檔案。

主動寫日記
Laravel logger 預設是紀錄 Warning 以上的錯誤(Error 在 Warning 之上,所以會被記錄),如果你想要更多資訊需要自己埋。

Laravel 的日誌提供了符合 RFC 5424 定義的八種日誌級別:emergency、alert、critical、error、warning、notice、info 和 debug。

八個級別不一定全都用到,一般只用到 4~5 個,也可以參考一下別人的使用情境

  • Trace - Only when I would be "tracing" the code and trying to find one part of a function specifically.
  • Debug - Information that is diagnostically helpful to people more than just developers (IT, sysadmins, etc.).
  • Info - Generally useful information to log (service start/stop, configuration assumptions, etc). Info I want to always have available but usually don't care about under normal circumstances. This is my out-of-the-box config level.
  • Warn - Anything that can potentially cause application oddities, but for which I am automatically recovering. (Such as switching from a primary to backup server, retrying an operation, missing secondary data, etc.)
  • Error - Any error which is fatal to the operation, but not the service or application (can't open a required file, missing data, etc.). These errors will force user (administrator, or direct user) intervention. These are usually reserved (in my apps) for incorrect connection strings, missing services, etc.
  • Fatal - Any error that is forcing a shutdown of the service or application to prevent data loss (or further data loss). I reserve these only for the most heinous errors and situations where there is guaranteed to have been data corruption or loss.

Ref


上一篇
12. Error x Error Handling x Exception
下一篇
14. Log X Notification x Slack
系列文
每天一篇文章30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言